<?php

namespace app\modules\models;

use Yii;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;

/**
 * This is the model class for table "shop_admin".
 *
 * @property string $adminid 主键ID
 * @property string $adminuser 管理员账号
 * @property string $adminpass
 * @property string $adminemail 管理员电子邮箱
 * @property string $logintime 登录时间
 * @property string $loginip 登录IP
 * @property string $createtime 创建时间
 */
class Admin extends ActiveRecord implements IdentityInterface
{
    public $rememberMe = true;
    public $repass;

    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return "{{%admin}}";
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['logintime', 'loginip', 'createtime'], 'integer'],
            [['adminuser', 'adminpass'], 'unique', 'targetAttribute' => ['adminuser', 'adminpass']],
            [['adminuser', 'adminemail'], 'unique', 'targetAttribute' => ['adminuser', 'adminemail']],
            ['adminuser','required','message' => '管理员账号不能为空','on' => ['login','seekpass','changeemail','changepass','adminadd']],
            ['adminpass','required','message' => '密码不能为空','on' => ['login','changepass','adminadd','changeemail']],
            ['rememberMe','boolean','on' => 'login'],
            ['adminpass','validatePass','on' => ['login','changeemail']],
            ['adminpass', 'validatePass', 'on' => ['login', 'changeemail']],
            ['adminemail', 'required', 'message' => '电子邮箱不能为空', 'on' => ['seekpass', 'adminadd', 'changeemail']],
            ['adminemail', 'email', 'message' => '电子邮箱格式不正确', 'on' => ['seekpass', 'adminadd', 'changeemail']],
            ['adminemail', 'unique', 'message' => '电子邮箱已被注册', 'on' => ['adminadd', 'changeemail']],
            ['adminuser', 'unique', 'message' => '管理员已被注册', 'on' => 'adminadd'],
            ['adminemail', 'validateEmail', 'on' => 'seekpass'],
            ['repass', 'required', 'message' => '确认密码不能为空', 'on' => ['changepass', 'adminadd']],
            ['repass', 'compare', 'compareAttribute' => 'adminpass', 'message' => '两次密码输入不一致', 'on' => ['changepass', 'adminadd']],

        ];
    }

    /**
     *
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'adminid' => 'Adminid',
            'adminuser' => 'Adminuser',
            'adminpass' => 'Adminpass',
            'adminemail' => 'Adminemail',
            'logintime' => 'Logintime',
            'loginip' => 'Loginip',
            'createtime' => 'Createtime',
        ];
    }

    public function validatePass()
    {
        if (!$this->hasErrors()){
            $data = self::find()->where(['adminuser' => $this->adminuser])->one();
            if (is_null($data)) {
                $this->addError("adminuser",'用户名错误');
                return false;
            }
            if (!Yii::$app->getSecurity()->validatePassword($this->adminpass,$data->adminpass)){
                $this->addError("adminpass","密码错误");
                return false;
            }
        }
    }

    public function validateEmail()
    {
        if(!$this->hasErrors()){
            $data = self::find()->where(['adminuser' => $this->adminuser,'adminemail' => $this->adminemail])->one();
            if (is_null($data)) {
                $this->addError('adminuser','管理员名称和邮箱不匹配');
                return false;
            }
        }
    }

    public function getAdmin()
    {
        return self::find()->where(['adminuser' => $this->adminuser])->one();
    }

    public function login($data)
    {
        $this->scenario = "login";
        if ($this->load($data) && $this->validate()) {
            return Yii::$app->admin->login($this->getAdmin(),$this->rememberMe ? 24*3600 :0);
        }
        return false;
    }

    public function seekPass($data)
    {
        $this->scenario = "seekpass";
        if($this->load($data) && $this->validate()) {
            $time = time();
            $token = $this->createToken($data['Admin']['adminuser'],$time);
            $mailer = Yii::$app->mailer
                ->compose('seekpass',['adminuser' => $data['Admin']['adminuser'],'time' => $time,'token' => $token]);
            $mailer->setFrom("372846553@qq.com");
            $mailer->setTo($data['Admin']['adminuser']);
            $mailer->setSubject("商城-找回密码");
            if($mailer->send()){
                return true;
            }
        }
        return false;
    }

    public function reg($data)
    {
        $this->scenario = 'adminadd';
        if($this->load($data) && $this->validate()) {
            $this->adminpass = Yii::$app->getSecurity()->generatePasswordHash($this->adminpass);
            if ($this->save(false)) {
                return true;
            }
            return false;
        }
        return false;
    }

    public function changePass($data)
    {
        $this->scenario = "changepass";
        if ($this->load($data) && $this->validate()) {
            return (bool)$this->updateAll(['adminpass' => md5($this->adminpass)],['adminuser' => $this->adminuser]);
        }
        return false;
    }

    public function changeEmail($data)
    {
        $this->scenario = "changeemail";
        if($this->load($data) && $this->validate()) {
            return (bool)$this->updateAll(['adminemail' => $this->adminemail],['adminuser' => $this->adminuser]);
        }
        return false;
    }
    public function createToken($adminuser,$time)
    {
        return md5(md5($adminuser).base64_encode(Yii::$app->request->userIP).md5($time));
    }

    public static function findIdentity($id)
    {
        return static::findOne($id);
    }

    public static function findIdentityByAccessToken($token, $type = null)
    {
        return null;
    }

    public function getId()
    {
        return $this->adminid;
    }

    public function getAuthKey()
    {
        return '';
    }

    public function validateAuthKey($authKey)
    {
        return true;
    }

    public function behaviors()
    {
        return [
            [
                'class' => TimestampBehavior::className(),
                'attributes' => [
                    ActiveRecord::EVENT_BEFORE_INSERT => ['createtime'],
                ],
            ],
        ];
    }

}
